import React, { useState, useEffect, useCallback } from "react"
import { Link, history } from "umi"
import { useLocation, useHistory } from "react-router"
import { Table, Button, Pagination, Select, message, Modal } from "antd"
const { Option } = Select
import { pageList, IcrConsultGroupPageListPam, IRecord, deletApi } from "@/services/consultationTeam"
import { getEnum, enumTypeList, ITypeEnum } from "@/services/common"
import { ColumnsType } from "antd/es/table"
import { ExclamationCircleOutlined } from "@ant-design/icons"
import styles from "./consultation.less"
import { slice } from "lodash"
const { confirm } = Modal







const consultation: React.FC = () => {

  /** *分页用***/
  const [current, setCurrent] = useState<number>(1) // 当前第几页
  const [size, setSize] = useState<number | undefined>(10) // 每页的数量
  const [total, setTotal] = useState<number>(0) // 数据总数
  const [pages, setPages] = useState<number>(1) // 总页数
  /** *分页用 end***/

  const [loading, setLoading] = useState<boolean>(false)
  const [selectList, setSelectList] = useState<Array<ITypeEnum>>([])// 状态列表
  const [status, setStatus] = useState<any>(null)// 会诊小组筛选的状态
  const [table, setTable] = useState<Array<IRecord>>([])// 列表


  // 查看组员
  const viewGroupMembers = (record: IRecord) => {

    history.push({
      pathname: "/consultationTeam/teamMember",
      query: {
        groupId: String(record.id)
      }
    })
  }

  // 删除
  const del = (record: IRecord, index: number) => {
    confirm({
      title: "温馨提示",
      icon: <ExclamationCircleOutlined />,
      content: "请确认是否删除该小组?",
      onOk() {
        deletFn(record.id, index)
      },
      onCancel() {
        // console.log(record, index)
      },
    })
  }

  // 编辑
  const edit = (record: IRecord) => {
    console.log(record)
  }

  const newTeam = () => {
    history.push("/consultationTeam/newTeam")
  }

  const columns: ColumnsType<any> = [
    {
      title: "分组名称",
      dataIndex: "groupName",
      key: "groupName",
      align: "center",
      width: "auto",
    },
    {
      title: "会诊对象",
      dataIndex: "target",
      key: "target",
      align: "center",
      width: "auto",
    },
    {
      title: "组长",
      dataIndex: "groupLeader",
      key: "groupLeader",
      align: "center",
      width: "auto",
    },
    {
      title: "小组人数",
      dataIndex: "nums",
      key: "nums",
      align: "center",
      width: "auto",
    },
    {
      title: "会诊小组状态",
      dataIndex: "statusRes",
      key: "statusRes",
      align: "center",
      width: "auto",
    },
    {
      title: "会诊得分",
      dataIndex: "grade",
      key: "grade",
      align: "center",
      width: "auto",
    },
    {
      title: "操作",
      align: "center",
      width: "250px",
      render: (text: string, record: any, index: number) => (
        <>
          {/* <Button onClick={() => edit(record)} type="primary" size="small" >编辑</Button>
          <Button onClick={() => del(record)} style={{ margin: "0 15px" }} danger size="small" >删除</Button>
          <Button onClick={() => viewGroupMembers(record)} size="small" >查看组员</Button> */}
          <span className="cursorPointer" onClick={() => edit(record)}  >编辑</span>
          <span className="cursorPointer" onClick={() => del(record, index)} style={{ margin: "0 15px" }}  >删除</span>
          <span className="cursorPointer" onClick={() => viewGroupMembers(record)}  >查看组员</span>
        </>
      )
    },

  ]



  // 切换页数
  const pageOnChange = (pageNumber: number, pageSize?: number | undefined) => {
    setSize(pageSize)
    setCurrent(pageNumber)
  }
  const showTotal = (total: number, range: number[]) => {
    const page = <div style={{ color: "#999" }}>
      共 {total} 条记录  第 <span style={{ color: "black" }} >{current}</span>   / {pages} 页
    </div>
    return page // `共${total}条记录  第${current}/${Math.ceil(total / 10)}页`
  }







  /**
  * 修改select
  */
  const onChangeSelect = (value: number | string) => {
    // console.log("选中的时候：", value)
    value === -100 ? setStatus(null) : setStatus(value)
  }

  // 删除某个小组
  const deletFn = async (id: number | string, index: number) => {
    setLoading(true)
    const [err, res] = await deletApi(id)
    setLoading(false)

    if (err) {
      return message.error(err.message)
    }
    table.splice(index, 1)
    setTable([...table])
    message.success(res?.message)
  }

  // 获取小组列表
  const initPageList = async () => {
    setLoading(true)
    let obj: IcrConsultGroupPageListPam = {
      status,
      current,
      size
    }

    const [err, res] = await pageList(obj)
    console.log(111, res)
    if (err) {
      setLoading(false)
      return message.error(err.message)
    }
    setLoading(false)

    setTable(res.data.records)
    setTotal(res.data.total)
    setPages(res.data.pages)
  }

  /**
 * 获取会诊小组状态列表字典
 */
  const getStateList = () => {
    getEnum(enumTypeList.consultGroupStatus, true).then(res => {
      res.data && (setSelectList(res.data))
    }).catch(err => {
      console.log(22222, err)
    })
  }





  // 初始化
  useEffect(() => {
    getStateList()
  }, [])

  // 顶部状态筛选监听


  useEffect(() => {
    initPageList()
  }, [status, current, size])




  return (
    <div className={styles.consultationWrap} >
      <div className={styles.allTitle} >
        <div style={{ display: "flex", justifyContent: "space-between", flex: 1 }} >
          <div>
            <span>全部小组</span>
            <span style={{ marginLeft: "10px" }}>({total}组)</span>
          </div>
          <Button type="primary" className={styles.newBtn} onClick={newTeam}  >新建小组</Button>
        </div>
      </div>

      <div className={styles.consultationContent} >
        <Select
          defaultValue={-100}
          style={{ width: 120, margin: "15px 0 0 15px" }}
          onSelect={(value: number | string) => { onChangeSelect(value) }}
        >
          {
            selectList && selectList.length > 0 ? selectList.map((item: ITypeEnum) => {
              return <Option key={item.value} value={item.value}>{item.str}</Option>
            }) : ""
          }
        </Select>
        <Table
          className={styles.tableHeight}
          loading={loading}
          bordered
          rowKey='id'
          columns={columns}
          dataSource={table}
          pagination={false}
        />

        <Pagination
          style={{ textAlign: "center", }}
          size="small"
          total={total}
          hideOnSinglePage={false}
          showQuickJumper
          pageSize={size}
          showTotal={showTotal}
          onChange={pageOnChange}
        />
      </div>

    </div >
  )
}

export default consultation
